<template>
    <div class="limited">
        <el-row>
            <el-col :span="6">
                <div class="left-box">
                    <el-tabs v-model="box_index_key" @tab-click="handleClick">
                        <el-tab-pane v-for="(item, index) in box_list_arr" :key="index" :label="item.label"
                            :name="item.name">
                            <div class="select-box flex_between">
                                <el-select size="mini" v-model="time" placeholder="请选择" @change="selectFun">
                                    <el-option v-for="item in time_data" :key="item.id" :label="item.name"
                                        :value="item.id">
                                    </el-option>
                                </el-select>
                                <el-select size="mini" v-model="shopid_yd" placeholder="请选择" @change="selectFun">
                                    <el-option v-for="item in getYunShopList" :key="item.id" :label="item.name"
                                        :value="item.id">
                                    </el-option>
                                </el-select>
                            </div>
                            <!-- 列表 -->
                            <LeftList :height="stateHooks.leftHeight" :templates="templates" :listData="listData"
                                :selectedIndex.sync="selectedIndex" @loadFun="loadFun" ref="leftListRef"
                                :lLoading="lLoading" :lNoMore="lNoMore" @clickItem="clickItem">
                                <div slot-scope="{row}" slot="ctype">
                                    <span>限定人群</span>
                                    <span style="margin-left: 10px">{{ row.ctype == 1 ? "所有客户" : "新客首次购买" }}</span>
                                </div>
                                <div slot-scope="{row}" slot="time_from_txt">
                                    <span>活动时效</span>
                                    <span style="margin-left: 10px">{{ row.time_from_txt}} 至 {{ row.time_to_txt}}</span>
                                </div>
                                <div slot-scope="{row}" slot="num_od" class="num_od">
                                    <span>订单总量 {{ row.num_od }}</span>
                                    <span style="margin-left: 10px">订单金额 {{ row.total_od }}</span>
                                </div>
                                <div slot-scope="{row}" slot="status_txt" class="status_txt">
                                    <span>{{ row.status_txt }}</span>
                                </div>
                            </LeftList>
                        </el-tab-pane>
                    </el-tabs>
                    <div class="iconBox">
                        <text class="icon-font search-icon" @click="addActivityList">&#xe606;</text>
                    </div>
                </div>
            </el-col>
            <el-col :span="18">
                <div class="rigth-box">
                    <template v-if="isEdit">
                        <addOrEdit 
                            :getYunShopList="getYunShopList" 
                            ref="marketingAddRef" 
                            @addOrEdt="addOrEdt"
                            :detailID="detailID"
                            :box_index_key="box_index_key"
                        >
                        </addOrEdit>
                    </template>
                    <template v-else>
                        <detaill 
                            ref="detaillRef" 
                            :detailID="detailID" 
                            @editStopTpBmFun="editStopTpBmFun"
                            @stopTpBmFun="stopTpBmFun"></detaill>
                    </template>
                </div>
            </el-col>
        </el-row>
    </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from '@vue/composition-api'
import LeftList from "@/pages/timeLimitsecOffer/components/leftList.vue"
import addOrEdit from "@/pages/timeLimitsecOffer/components/addOrEdit.vue"
import detaill from "@/pages/timeLimitsecOffer/components/detaill.vue"
import config from "@/js/conf/Config.js"
import { useCommonHooks } from '@/hooks/useCommonHooks.js'
const maxPnum = 20

// 获取当前组件实例
const { proxy } = getCurrentInstance()

// 使用全局状态
const { stateHooks } = useCommonHooks()

const box_index_key = ref("2")
const box_list_arr = ref([{
    label: "进行中",
    name: "2",
}, {
    label: "未开始",
    name: "1",
}, {
    label: "已失效",
    name: "3",
}])

const templates = ref([{
    type: "init",
    key: "shop_name",
}, {
    type: "init",
    key: "title",
},
{
    type: "slot", // Approaching
    key: "ctype",
},
{
    type: "slot",
    key: "time_from_txt",
    class: "ps"
},
{
    type: "slot",
    key: "num_od",
}, {
    type: "slot",
    key: "status_txt",
}])

const listData = ref([])

const getYunShopList = ref([{
    name: "全部云店",
    id: 0,
}])

const time_data = ref([{
    id: 0,
    name: "全部日期",
},
{
    id: "1",
    name: "今日",
},
{
    id: "2",
    name: "本月",
},
{
    id: "3",
    name: "本季",
},
{
    id: "4",
    name: "本年",
},
{
    id: "5",
    name: "自定义",
},
])

const time = ref(0)
const shopid_yd = ref(0)
const pfrom = ref(0)
const lLoading = ref(false)
const lNoMore = ref(false)
const marketingAddRef = ref(null)

// 状态切换
const handleClick = () => {
    selectedIndex.value = 0
    getEventLs(true)
}

// 选择分店
const selectFun = (e) => {
    getEventLs(true)
}

const loadFun = () => {
    if (lNoMore.value) return
    pfrom.value += 20
    getEventLs(false)
}

// 编辑
const isEdit = ref(false)
const detailID = ref(null)
const selectedIndex = ref(0)
const recordSelectedIndex = ref(0)
const clickItem = (index) => {
    isEdit.value = false
    selectedIndex.value = index
    recordSelectedIndex.value = index
    detailID.value = listData.value[index]?.id
}

const getEventLs = async (t = true) => {
    lLoading.value = true
    if (t == true) {
        pfrom.value = 0
        listData.value = []
    }
    let param = {
        shopid_yd: shopid_yd.value,
        st: box_index_key.value,
        pnum: maxPnum,
        pfrom: pfrom.value,
        stime: "",
        dtime: "",
        time: time.value,
    }
    try {
        let res = await proxy.$api({ url: config.YX_XS_EVENT_LS, data: param })
        lLoading.value = false
        if (res.status == 1) {
            let result = res.data
            if (result.ls) {
                listData.value.push(...result.ls)
                // 确保索引在有效范围内
                const validIndex = Math.min(selectedIndex.value, listData.value.length - 1)
                detailID.value = listData.value[validIndex]?.id
                if (res.status == 1 && result.ls.length < maxPnum) {
                    lNoMore.value = true
                } else {
                    lNoMore.value = false
                }
            } else {
                lNoMore.value = true;
            }
        } else {
            lNoMore.value = true
        }
    } catch (error) {
        lLoading.value = false
        lNoMore.value = true
    } finally {
        lLoading.value = false
    }
}

//  获取云店列表
const getYunShopLsFun = async () => {
    let url = config.YUN_SHOP_LS
    let param = {}
    try {
        let res = await proxy.$api({ url: url, data: param })
        if (res.status == 1) {
            getYunShopList.value.push(...res.data)
        }
    } catch (error) {
        console.error('获取云店列表失败:', error)
    }
}

// 如果是编辑页面，设置某些值不能编辑
const isDisbableInfo = ref({
    type: false,
})
const addActivityList = () => {
    isEdit.value = true
    selectedIndex.value = null
    detailID.value = ''
    isDisbableInfo.value.type = false
    if (marketingAddRef.value) {
        isDisbableInfo.value.type = false
        marketingAddRef.value.restFun()
        marketingAddRef.value.objectForm.act = 'add'
        marketingAddRef.value.objectForm.status = 1
    }
}

const addOrEdt = (e) => {
    console.log('e=>', e)
    box_index_key.value = e.status.toString()
    isEdit.value = false
    if (e.type == 'add' || e.type == 'del' || e.type == 'edt') {
        selectedIndex.value = 0
        refreshFun()
        getEventLs(true)
    } else {
        selectedIndex.value = recordSelectedIndex.value
        detailID.value = listData.value[recordSelectedIndex.value].id
    }
}

const refreshFun = () => {
    lNoMore.value = false
    lLoading.value = false
    pfrom.value = 0
    detailID.value = ''
    listData.value = []
}

// 处理编辑和停止事件
const editStopTpBmFun = (data) => {
    console.log('data=>', data)
    if (data.type == 'edt') {
        // 切换到编辑模式
        isEdit.value = true
        detailID.value = data?.id
        selectedIndex.value = recordSelectedIndex.value
        // 等待下一个tick确保组件已更新
        proxy.$nextTick(() => {
            if (marketingAddRef.value) {
                // marketingAddRef.value.getEventInfo()
                marketingAddRef.value.objectForm.act = 'edt'
                marketingAddRef.value.objectForm.id = data?.id
            }
        })
    } else if (data.type === 'stop') {
        // 处理停止逻辑，可能需要刷新列表
        getEventLs(true)
    }
}

// 处理停止事件
const stopTpBmFun = (data) => {
    console.log('stopTpBmFun called with:', data)
    // 刷新列表
    getEventLs(true)
}

onMounted(() => {
    getEventLs()
    getYunShopLsFun()
})
</script>

<style lang="scss" scoped>
div {
    box-sizing: border-box;
}

.limited {

    .left-box,
    .rigth-box {
        width: 100%;
        padding: 10px 10px 0 10px;
        height: 100vh;
        position: relative;
        border-right: 1px solid #e6e6e6;

        .iconBox {
            position: absolute;
            top: 0px;
            right: 13px;
            font-size: 26px;
            cursor: pointer;

            .search-icon {
                font-size: 20px;
                color: #333;
            }
        }

        .marketing-add {
            width: 100%;
        }
    }

    .status_txt {
        position: absolute;
        right: 20px;
        top: 33px;
    }

    .list_btn {
        position: absolute;
        bottom: 10px;
        right: 20px;
        z-index: 9;
    }
}
</style>